package cn.edu.zhku.util;

public class InviteCodeGenerator {

    private static char conv[][] = new char[10][3];

    static {
        conv[0] = new char[] {'e', 'f', 'v'};
        conv[1] = new char[] {'t', 'z'};
        conv[2] = new char[] {'x', 'a', 'o'};
        conv[3] = new char[] {'p', 'k'};
        conv[4] = new char[] {'b', 'w', 'y'};
        conv[5] = new char[] {'c', 'l'};
        conv[6] = new char[] {'g', 's', 'd'};
        conv[7] = new char[] {'h', 'm'};
        conv[8] = new char[] {'u', 'r', 'j'};
        conv[9] = new char[] {'q', 'i', 'n'};
    }

    private static String convert(String code) {
        char c[] = code.toCharArray();
        // 数字映射为字母
        for (int i=0;i<c.length;++i) {
            if (c[i]>='0' && c[i]<='9') {
                if (c[i]<'8' && (c[i]&1)==1) {
                    int x = (int) (Math.random()*100);
                    if (x >= 50)
                        c[i] = conv[c[i]-'0'][1];
                    else
                        c[i] = conv[c[i]-'0'][0];
                } else {
                    int x = (int) (Math.random()*100);
                    if (x < 33) {
                        c[i] = conv[c[i]-'0'][1];
                    } else if (x < 66) {
                        c[i] = conv[c[i]-'0'][2];
                    } else {
                        c[i] = conv[c[i]-'0'][0];
                    }
                }
            }
        }
        return new String(c);
    }

    public static String generate(Integer userId) {
        String code = "" + userId + System.currentTimeMillis();
        return convert(code);
    }

}
